package com.rem.concurrency.juc.my13Single;

/**
 * DCL 懒汉式
 * 多线程下 双重加锁 并且加volatile 禁止指定重排
 *
 * @author Rem
 * @date 2021-03-10
 */

public class LazyMan2 {

    private LazyMan2() {
        System.out.println(Thread.currentThread().getName() + "ok");
    }

    private volatile static LazyMan2 lazyMan;


    /**
     * 双层检测的锁模式 DCL懒汉式
     *
     * @return
     */
    public static LazyMan2 getLazyMan() {
        //加锁操作
        if (lazyMan == null) {
            //加锁
            synchronized (LazyMan2.class) {
                if (lazyMan == null) {
                    //不是一个原子性的操作
                    lazyMan = new LazyMan2();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                LazyMan2 lazyMan = LazyMan2.getLazyMan();
                System.out.println(lazyMan);
            }).start();
        }
    }
}